package com.example.mitao.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.example.mitao.BaseApplication;
import com.lamfire.utils.StringUtils;


import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static android.content.Context.TELEPHONY_SERVICE;

public class OsUtils {

    private static final String TAG = OsUtils.class.getSimpleName();

    public OsUtils() {
    }

    public static String getProcessName(Context cxt, int pid) {
        String def = "";
        ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        List runningApps = am.getRunningAppProcesses();
        if (runningApps == null) {
            return def;
        } else {
            Iterator var5 = runningApps.iterator();

            ActivityManager.RunningAppProcessInfo procInfo;
            do {
                if (!var5.hasNext()) {
                    return def;
                }

                procInfo = (ActivityManager.RunningAppProcessInfo) var5.next();
            } while (procInfo.pid != pid);

            return procInfo.processName;
        }
    }

    /**
     * 判断是否已安装指定包名的APP
     *
     * @param packagename
     * @return
     */
    public static boolean isAppInstalled(String packagename) {
        PackageManager pm = BaseApplication.getContext().getPackageManager();
        boolean installed = false;
        try {
            pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES);
            installed = true;
        } catch (PackageManager.NameNotFoundException e) {
            installed = false;
        }
        return installed;
    }


    /**
     * 这是使用adb shell命令来获取mac地址的方式(通过eth)
     *
     * @return
     */

    public static String getMacEth() {

        String macSerial = null;
        String str = "";
        try {
            Process pp = Runtime.getRuntime().exec("cat /sys/class/net/eth0/address ");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            for (; null != str; ) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();// 去空格
                    break;
                }
            }

        } catch (IOException ex) {

            // 赋予默认值
            ex.printStackTrace();

        }

        if (StringUtils.isEmpty(macSerial)) {
            macSerial = getMacWlan();
        }

        return macSerial.toUpperCase();

    }

    /**
     * 这是使用adb shell命令来获取mac地址的方式 (通过wlan)
     *
     * @return
     */
    public static String getMacWlan() {

        String macSerial = null;
        String str = "";
        try {
            Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address ");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            for (; null != str; ) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();// 去空格
                    break;
                }
            }

        } catch (IOException ex) {

            // 赋予默认值
            ex.printStackTrace();

        }

        return macSerial;

    }



    // ******************************************************************************************************************

    /**
     * 根据wifi信息获取本地mac (适用6.0以下 需要权限 <uses-permission
     * android:name="android.permission.ACCESS_WIFI_STATE" />)
     *
     * @param context
     * @return
     */
//    public static String getLocalMacAddressFromWifiInfo(Context context) {
//        WifiManager wifi = (WifiManager) context
//                .getSystemService(Context.WIFI_SERVICE);
//        WifiInfo winfo = wifi.getConnectionInfo();
//        String mac = winfo.getMacAddress();
//        return mac;
//    }



    /**
     * 2018年6月28日
     * 作者：csj
     * 方法描述：判断服务是否在运行
     *
     * @param context
     * @param ServiceName
     * @return
     */
    public static boolean isServiceRunning(Context context, String ServiceName) {
        if (("").equals(ServiceName) || ServiceName == null)
            return false;
        ActivityManager myManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) myManager.getRunningServices(30);
        for (int i = 0; i < runningService.size(); i++) {
            if (runningService.get(i).service.getClassName().toString().contains(ServiceName)) {
                return true;
            }
        }
        return false;
    }


    /**
     * (第一种，部分机型不可行)
     * 手机是否开启位置服务，如果没有开启那么所有app将不能使用定位功能
     */
    public static boolean isLocServiceEnable(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }
        return false;
    }

    /**
     * （第二种，兼容所有机型）
     * 判断位置服务是否打开
     *
     * @return
     */
    public static boolean isLocationEnabled() {
        int locationMode = 0;
        String locationProviders;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                locationMode = Settings.Secure.getInt(BaseApplication.getContext().getContentResolver(), Settings.Secure.LOCATION_MODE);
            } catch (Settings.SettingNotFoundException e) {
                e.printStackTrace();
                return false;
            }
            return locationMode != Settings.Secure.LOCATION_MODE_OFF;
        } else {
            locationProviders = Settings.Secure.getString(BaseApplication.getContext().getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            return !StringUtils.isEmpty(locationProviders);
        }
    }

    /**
     * 直接跳转至位置信息设置界面
     */
    public static void openLocation(Context context) {
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        context.startActivity(intent);
    }

    /**
     * 让用户去打开wifi
     */
    public static void openWifi1(Context context) {
        //第一种
//      Intent intent = new Intent();
//      intent.setAction("android.net.wifi.PICK_WIFI_NETWORK");
//      startActivity(intent);

        //第二种
//      Intent wifiSettingsIntent = new Intent("android.settings.WIFI_SETTINGS");
//      startActivity(wifiSettingsIntent);

        //第三种
//      Intent intent = new Intent();
//      if(android.os.Build.VERSION.SDK_INT >= 11){
//          //Honeycomb
//          intent.setClassName("com.android.settings", "com.android.settings.Settings$WifiSettingsActivity");
//       }else{
//          //other versions
//           intent.setClassName("com.android.settings", "com.android.settings.wifi.WifiSettings");
//       }
//       startActivity(intent);
        //第四种
        Intent wifiSettingsIntent = new Intent(Settings.ACTION_WIFI_SETTINGS);//"android.settings.WIFI_SETTINGS"
        wifiSettingsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
        context.startActivity(wifiSettingsIntent);
    }

    /**
     * 反射获取 getSubscriberId ，既imsi  (应该不适用于Android Q了)
     *
     * @param subId
     * @return
     */
    public static String getSubscriberId(int subId) {
        TelephonyManager telephonyManager = (TelephonyManager) BaseApplication.getContext().getSystemService(TELEPHONY_SERVICE);// 取得相关系统服务
        Class<?> telephonyManagerClass = null;
        String imsi = null;
        try {
            telephonyManagerClass = Class.forName("android.telephony.TelephonyManager");

            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
                Method method = telephonyManagerClass.getMethod("getSubscriberId", int.class);
                imsi = (String) method.invoke(telephonyManager, subId);
            } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.LOLLIPOP) {
                Method method = telephonyManagerClass.getMethod("getSubscriberId", long.class);
                imsi = (String) method.invoke(telephonyManager, (long) subId);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        Log.i(TAG, "IMSI==" + imsi);
        return imsi;
    }

    /**
     * 反射获取 getSubscriptionId ，既 subid  (应该不适用于Android Q了)
     *
     * @param slotId 卡槽位置（0，1）
     * @return
     */
    public static int getSubscriptionId(int slotId) {
        try {
            Method datamethod;
            int setsubid = -1;//定义要设置为默认数据网络的subid
            //获取默认数据网络subid   getDefaultDataSubId
            Class<?> SubscriptionManager = Class.forName("android.telephony.SubscriptionManager");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { // >= 24  7.0
                datamethod = SubscriptionManager.getDeclaredMethod("getDefaultDataSubscriptionId");
            } else {
                datamethod = SubscriptionManager.getDeclaredMethod("getDefaultDataSubId");
            }
            datamethod.setAccessible(true);
            int SubId = (int) datamethod.invoke(SubscriptionManager);


            Method subManagermethod = SubscriptionManager.getDeclaredMethod("from", Context.class);
            subManagermethod.setAccessible(true);
            Object subManager = subManagermethod.invoke(SubscriptionManager, BaseApplication.getContext());

            //getActiveSubscriptionInfoForSimSlotIndex  //获取卡槽0或者卡槽1  可用的subid
            Method getActivemethod = SubscriptionManager.getDeclaredMethod("getActiveSubscriptionInfoForSimSlotIndex", int.class);
            getActivemethod.setAccessible(true);
            Object msubInfo = getActivemethod.invoke(subManager, slotId);  //getSubscriptionId

            Class<?> SubInfo = Class.forName("android.telephony.SubscriptionInfo");

            //slot0   获取卡槽0的subid
            int subid = -1;
            if (msubInfo != null) {
                Method getSubId0 = SubInfo.getMethod("getSubscriptionId");
                getSubId0.setAccessible(true);
                subid = (int) getSubId0.invoke(msubInfo);
            }
            Log.i(TAG, "slotId=" + slotId + ", subid=" + subid);
            return subid;
        } catch (Exception e) {
            Log.e(TAG, e.getLocalizedMessage());
        }
        return -1;
    }

    /**
     * 获取运营商 IMSI (应该不适用于Android Q了)
     * 默认为 IMEI1对应的 IMSI
     *
     * @return
     */
    public static String getSimOperator() {
        TelephonyManager telephonyManager = (TelephonyManager) BaseApplication.getContext().getSystemService(TELEPHONY_SERVICE);// 取得相关系统服务
        return telephonyManager.getSimOperator();
    }

    /**
     * 根据卡槽位置 获取运营商 IMSI (应该不适用于Android Q了)
     *
     * @param slotId 卡槽位置（0，1）
     * @return
     */
    public static String getSimOperator(int slotId) {
        int subid = getSubscriptionId(slotId);
        if (subid == -1) {
            return "";
        }

        String imsi = getSubscriberId(subid);
        if (!StringUtils.isEmpty(imsi)) {
            return imsi;
        }

        return "";
    }



    /**
     * 跳转系统设置页
     * @param ctx
     */
    public static void toSetting(Context ctx){
        Intent intent =  new Intent(Settings.ACTION_SETTINGS);
        if(!(ctx instanceof Activity)){
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        ctx.startActivity(intent);
    }

}
